# 分析北向资金
# 北向资金流入会引发股市小幅度上涨
# 下方是未完成的代码，需要再做调整

from datacache import get_index_stock_data
import pandas as pd

def main():
    index_code = '000300' # 沪深300为 000300 中证500 000905
    start_time = '20230101'
    end_time = '20240101'
    df = get_index_stock_data(index_code, start_time ,end_time)
    df.set_index("日期", inplace=True)
    # 这里读取沪股通和深股通当日成交净买额， 如今政策变了，需要再做调整
    df['当日成交净买额_hgt'] = hgt['当日成交净买额']
    df['当日成交净买额_sgt'] = sgt['当日成交净买额']
    # 深股通和沪股通之和为净流入
    df['净流入'] = df[['当日成交净买额_hgt', '当日成交净买额_sgt'].sum(axis=1)]
    df['净流入'] = df['净流入'] / 100
    # 用不到这两列了，可以删掉
    del df['当日成交净买额_hgt'], df['当日成交净买额_sgt']

    # 计算未来N天涨跌幅度
    df['未来1天涨跌幅度'] = df['收盘'].shift(-1) / df['收盘'].shift(-1) - 1
    df['未来3天涨跌幅度'] = df['收盘'].shift(-3) / df['收盘'].shift(-1) - 1
    df['未来5天涨跌幅度'] = df['收盘'].shift(-5) / df['收盘'].shift(-1) - 1

    # 根据日期筛选数据
    df = df[df.index <= pd.to_datetime('2023-01-01')]

    # 創建空表格
    result = pd.DataFrame()
    # 筛选净流入大于flow的数据
    for flow in [0, 10, 20, 30, 40, 50]:
        t_df = df[df['净流入'] > flow]
        result.loc[flow, '出现次数'] = t_df.shape[0]
        # 计算未来N天数据
        for i in [1, 3, 5]:
            result.loc[flow, '未来%d日上涨次数' % i] = t_df[t_df]
            result.loc[flow, '未来%d日上涨平均涨幅' % i] = t_df[t_df]

    for i in [1, 3, 5]:
        result['未来%d日上涨概率' % i] = result['未来%d日上涨次数']
    print(df)

if __name__ == "__main__":
    main()